from XlementFitting.FileProcess.JsonFormat import check_unpredicted_json_format
from XlementFitting.FileProcess.Json2Data import read_and_process_json, get_fitting_options
from XlementFitting.FileProcess.Data2Json import process_and_save_json
from XlementFitting import PartialBivariate, GlobalBivariate, LocalBivariate, SingleCycleFitting3
from XlementFitting.FunctionalFittingOneTwo import GlobalBivariate12  # ← 新增导入
path = "SourceData/二价模型/1-2.json"
print(check_unpredicted_json_format(path))
fitting_options, df, time0, f, time0_dict = read_and_process_json(path)
print(time0)
print(f"df:\n{df},\nf:{f},\noptions:{fitting_options}")
# df.to_excel("test.xlsx")
origin_df = df.copy()
if f == 103:
    r,p,i = PartialBivariate(
        data_frame=df,
        time0=time0,
        options=get_fitting_options(fitting_options),
        write_file=False,
        excel_path='FittingResultFile'
    )
elif f == 101:
    r,p,i = LocalBivariate(
        data_frame=df,
        time0=time0,
        options=get_fitting_options(fitting_options),
        write_file=False,
        excel_path='FittingResultFile'
    )
elif f == 102:
    r,p,i = GlobalBivariate(
        data_frame=df,
        time0=time0,
        options=get_fitting_options(fitting_options),
        write_file=False,
        excel_path='FittingResultFile'
    )
elif f == 108:
    print(time0_dict)
    r,p,i = SingleCycleFitting3(
        data_frame=df,
        time0_dict=time0_dict,
        options=get_fitting_options(fitting_options)
    )
elif f == 104:
    # 1:2 全局拟合（默认独立双位点）；如需顺序两步，传 model12_type="sequential_two_step"
    r,p,i = GlobalBivariate12(
        data_frame=df,
        time0=time0,
        options=get_fitting_options(fitting_options),
        write_file=False,
        excel_path='FittingResultFile',
        model12_type="independent_two_sites",      # or "sequential_two_step"
        seq_use_R1_plus_2R2=True
    )
elif f == 105:
    # 1:2 全局拟合（默认独立双位点）；如需顺序两步，传 model12_type="sequential_two_step"
    r,p,i = GlobalBivariate12(
        data_frame=df,
        time0=time0,
        options=get_fitting_options(fitting_options),
        write_file=False,
        excel_path='FittingResultFile',
        model12_type="sequential_two_step",      # or "sequential_two_step"
        seq_use_R1_plus_2R2=True
    )

# 获取 DataFrame 的行数和列数
rows, cols = origin_df.shape

# 获取要插入的数据的行数和列数
new_rows, new_cols = p.shape # type: ignore
print(f"输出:\n{p}")
print(f"输出的大小:{p.shape},输入的大小:{origin_df.shape}") # type: ignore
# 确保新数据不会超出 DataFrame 的边界
if new_rows > rows - 1 or new_cols > cols - 1:
    raise ValueError("新数据的大小超出了 DataFrame 的可用空间")

# 将新数据插入到 DataFrame 中，从第二列第二行开始
origin_df.iloc[1:1+new_rows, 1:1+new_cols] = p # type: ignore
# origin_df.to_excel("test_output.xlsx")
process_and_save_json(
    json_file_path=path,
    df=origin_df,
    output_json_path="SourceData/二价模型/1-2-fit.json",
    fitting_result = r
)
# print(origin_df)